trigger ChangeOwner on Opportunity (before Insert , Before Update) {
    /*
    * This trigger is used to change the owner of Account and
    * Opportunity to ULA Traditional Contact center manager when the
    * opportunity stage name is changed to Exited or cambio de ciclo. 
    */
    Map<Id,RecordType> map_RecordType = new Map<Id,RecordType>([ Select Id, DeveloperName from RecordType Where sObjectType='Opportunity' AND (DeveloperName='ULA_Traditional_Application_Layout' OR DeveloperName='ULA_Working_Adults_Application_Layout')]);
    
    Id UlAManager;
    Id UlaSupervisor; 
    List<User> usr = [Select id, UserRole.name ,IsActive from user where isActive=true AND (UserRole.Name='ULA Traditional Contact Center Manager' OR UserRole.Name='ULA Working Adults Call Center Supervisor')];
    for(User u : usr)
    {
       if( u.UserRole.Name.equalsIgnoreCase('ULA Traditional Contact Center Manager'))
        {
            UlAManager= u.Id;
        }
        else
        {
            UlaSupervisor = u.id;
        }
    }
    Map<string,string> mapIds = new Map<string,string>();
    for(Opportunity opp : Trigger.New)
    {
        if(opp.RecordTypeId!= null && map_RecordType.containsKey(opp.RecordTypeId) && ( opp.StageName.equalsIgnorecase('Exited') || opp.StageName.equalsIgnorecase('cambio de ciclo'))  )
        {
            if( map_RecordType.get(opp.RecordTypeId).DeveloperName.equalsIgnorecase('ULA_Traditional_Application_Layout') && UlAManager != null)
            {
                opp.ownerid= UlAManager;
                mapIds.put(opp.AccountId,UlAManager);                
            }
        }
    }
    List<Account> acc = [select id,ownerid from account where id in: mapIds.keyset()];
    List<Account> updateAccs = new List<Account>();
    for(Account a:acc)
    {
        if(mapIds.containsKey(a.id))
        {
            a.ownerid = mapIds.get(a.id);
            updateAccs.add(a);
        }
    }
    if(!updateAccs.isEmpty())
    {
    	update updateAccs;
    }
}